<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="时间" prop="advertiserId">
              <el-date-picker
                v-model="time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleTimeChange"
              />
            </el-form-item>
            <el-form-item label="广告主id" prop="advertiserId">
               <el-input v-model="queryParams.advertiserId" placeholder="请输入广告主id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="素材id" prop="materialId">
              <el-input v-model="queryParams.materialId" placeholder="请输入素材的文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="素材名" prop="filename">
              <el-input v-model="queryParams.filename" placeholder="请输入素材的文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="视频标签" prop="labels">
              <el-input v-model="queryParams.labels" placeholder="请输入视频标签" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="素材来源" prop="source">
              <el-input v-model="queryParams.source" placeholder="请输入素材来源" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oce:material:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Refresh" @click="synchronization" v-hasPermi="['oce:material:syncMaterial']">同步素材库 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oce:material:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oce:material:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:material:export']">导出</el-button>
          </el-col>
          <div class="flex items-center text-[12px] tips">
            <div class="ml-[10px] label">当前操作帐户：</div>
            <div class="val" :class="appStore.accountName ? 'text-[#409EFF]' : 'text-[#f00]'">{{ appStore.accountName || '未设置' }}</div>
          </div>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="素材" align="center" width="250" prop="materialId">
          <template #default="{ row }">
            <div>素材名: {{ row.filename }}</div>
            <div>
              素材id:
              <el-text type="danger">
                <span class="underline cursor-pointer" v-copyText="row.materialId">{{ row.materialId }}</span>
              </el-text>
            </div>
            <div>
              广告主id:
              <el-text type="danger">
                <span class="underline cursor-pointer" v-copyText="row.advertiserId">{{ row.advertiserId }}</span>
              </el-text>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="视频首帧" align="center" prop="posterUrl">
          <template #default="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.posterUrl" :fit="fit"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="视频地址" align="center" prop="url">
          <template #default="{ row }">
            <video style="width: 100px; height: 100px" :src="row.url" :fit="fit"></video>
          </template>
        </el-table-column>
        <el-table-column label="视频信息" align="center">
          <template #default="{ row }">
            <div>{{ row.width }} * {{ row.height }}</div>
            <div>{{ formatPrice(row.size / 1024 / 1024) }} M</div>
          </template>
        </el-table-column>
        <el-table-column label="视频标签" align="center" prop="labels">
          <template #default="{ row }">
            <div>{{ row.labels == '[]' ? '' : row.labels }}</div>
          </template>
        </el-table-column>
        <el-table-column label="视频格式" align="center" prop="format" />
        <el-table-column label="视频时长" align="center" prop="duration">
          <template #default="{ row }">
            <div>{{ formatPrice(row.duration / 60).replace('.', ':') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="createTime" />
        <el-table-column label="素材来源" align="center" prop="source">
          <template #default="{ row }">
            <div>{{ row.source == 'AD_SITE' ? 'ad后台本地上传' : '未知' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="素材评估" align="center" prop="isFirstPublishMaterial">
          <template #default="{ row }">
            <div>
              {{ row.isFirstPublishMaterial == 1 ? '首发素材' : '' }}
              {{ row.isAdHighQualityMaterial == 1 ? '优质素材' : '' }}
              {{ row.isAdLowQualityMaterial == 1 ? '低质素材' : '' }}
              {{ row.isCarryMaterial == 1 ? '同质化挤压严重素材' : '' }}
              {{ row.isSimilarMaterial == 1 ? '同质化素材风险-排队投放素材' : '' }}
              {{ row.isSimilarQueueMaterial == 1 ? '是否同质化素材风险-未投放预计排队素材' : '' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="「存在搬运打压风险」属性最后一次更新时间" align="center" prop="attributesModifyTime" />
        <el-table-column label="低质原因" align="center" prop="adLowQualitySuggestions" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oce:material:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oce:material:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Material" lang="ts">
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, syncMaterial } from '@/api/advertisement/videoMaterial';
import { MaterialVO, MaterialQuery, MaterialForm } from '@/api/advertisement/videoMaterial/types';
import { formatPrice, formatYmd } from '@/utils';
import dayjs from 'dayjs';
import { useAppStore } from '@/store/modules/app';
const appStore = useAppStore();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const materialList = ref<MaterialVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const newAdvertiserId = ref();
const queryFormRef = ref<ElFormInstance>();
const materialFormRef = ref<ElFormInstance>();
const time = ref([dayjs().subtract(7, 'day').format('YYYY-MM-DD') + ' 00:00:00', dayjs().format('YYYY-MM-DD') + ' 23:59:59']);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MaterialForm = {
  materialId: undefined,
  accountId: undefined,
  advertiserId: undefined,
  id: undefined,
  filename: undefined,
  labels: undefined,
  posterUrl: undefined,
  url: undefined,
  width: undefined,
  height: undefined,
  size: undefined,
  format: undefined,
  signature: undefined,
  duration: undefined,
  bitRate: undefined,
  source: undefined,
  starAuthorId: undefined,
  isFirstPublishMaterial: undefined,
  isAdHighQualityMaterial: undefined,
  isAdLowQualityMaterial: undefined,
  isCarryMaterial: undefined,
  isSimilarMaterial: undefined,
  isSimilarQueueMaterial: undefined,
  isSimilarExpectedQueueMaterial: undefined,
  attributesModifyTime: undefined,
  adLowQualitySuggestions: undefined
};
const data = reactive<PageData<MaterialForm, MaterialQuery>>({
  form: { ...initFormData },
  queryParams: {
    startTime: undefined,
    endTime: undefined,
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    materialId: undefined,
    advertiserId: undefined,
    filename: undefined,
    labels: undefined,
    posterUrl: undefined,
    url: undefined,
    width: undefined,
    height: undefined,
    size: undefined,
    format: undefined,
    signature: undefined,
    duration: undefined,
    bitRate: undefined,
    source: undefined,
    starAuthorId: undefined,
    isFirstPublishMaterial: undefined,
    isAdHighQualityMaterial: undefined,
    isAdLowQualityMaterial: undefined,
    isCarryMaterial: undefined,
    isSimilarMaterial: undefined,
    isSimilarQueueMaterial: undefined,
    isSimilarExpectedQueueMaterial: undefined,
    attributesModifyTime: undefined,
    adLowQualitySuggestions: undefined,
    params: {}
  },
  rules: {
    materialId: [{ required: true, message: '素材id不能为空', trigger: 'blur' }],
    accountId: [{ required: true, message: '管家账号id不能为空', trigger: 'blur' }],
    advertiserId: [{ required: true, message: '广告主id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询素材列表 */
const getList = async () => {
  loading.value = true;
  if (time.value.length > 0 && (time.value[0].length > 12 || time.value[1].length > 12)) {
    queryParams.value.startTime = time?.value[0];
    queryParams.value.endTime = time?.value[1];
  } else {
    queryParams.value.startTime = time?.value[0] + ' 00:00:00';
    queryParams.value.endTime = time?.value[1] + ' 23:59:59';
  }
  const res = await listMaterial(queryParams.value);
  materialList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const handleTimeChange = (val) => {
  console.log(val);
};
// 传值
const getAdvertiserId = async (val) => {
  queryParams.value.advertiserId = val; // 测试才屏蔽
  form.value.advertiserId = val;
  newAdvertiserId.value = val;
  await getList();
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  materialFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialVO[]) => {
  ids.value = selection.map((item) => item.materialId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加素材';
};
// 同步
const synchronization = async () => {
  let params = {
    accountId: appStore.accountId,
    advertiserId: queryParams.value.advertiserId,
    startTime: time?.value[0].substr(0, 10),
    endTime: time?.value[1].substr(0, 10)
  };
  await syncMaterial(params);
  proxy?.$modal.msgSuccess('同步成功，请稍后刷新');
  await getList();
};
/** 修改按钮操作 */
const handleUpdate = async (row?: MaterialVO) => {
  reset();
  const _materialId = row?.materialId || ids.value[0];
  const res = await getMaterial(_materialId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改素材';
};

/** 提交按钮 */
const submitForm = () => {
  materialFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.materialId) {
        await updateMaterial(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMaterial(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialVO) => {
  const _materialIds = row?.materialId || ids.value;
  await proxy?.$modal.confirm('是否确认删除素材编号为"' + _materialIds + '"的数据项？').finally(() => (loading.value = false));
  await delMaterial(_materialIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oce/material/export',
    {
      ...queryParams.value
    },
    `material_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  // time时间的开始时间默认选中当向前推7天，结束时间默认选中当天
  time.value = [dayjs().subtract(7, 'day').format('YYYY-MM-DD') + ' 00:00:00', dayjs().format('YYYY-MM-DD') + ' 23:59:59'];
  getList();
});
</script>
